package com.dkakunsi.monev.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.dkakunsi.monev.entity.Kegiatan;
import com.dkakunsi.monev.entity.RealisasiDana;
import com.dkakunsi.monev.util.MonevDataException;

@Repository("RealisasiDanaHibernateRepository")
public class RealisasiDanaDao extends GenericDao<RealisasiDana> {
	@SuppressWarnings("unchecked")
	public List<RealisasiDana> get(Kegiatan kegiatan) throws MonevDataException {
		Query query = getSession().createQuery("SELECT r FROM RealisasiDana r WHERE r.kegiatan = :kegiatan ORDER BY r.bulan");
		query.setParameter("kegiatan", kegiatan);
		
		return checkNull(query.list());
	}
	
	@Override
	public void save(RealisasiDana r) {
		super.save(isExist(r));
	}

	@SuppressWarnings("unchecked")
	protected RealisasiDana isExist(RealisasiDana r) {
		Query query = getSession().createQuery("SELECT r FROM RealisasiDana r WHERE r.kegiatan = :kegiatan AND r.bulan = :bulan");
		query.setParameter("kegiatan", r.getKegiatan());
		query.setParameter("bulan", r.getBulan());
		
		try {
			List<RealisasiDana> ls = checkNull(query.list());
			if(ls.size() <= 0)
				throw new MonevDataException();
			
			RealisasiDana rd = ls.get(0);
			rd.setJumlah(r.getJumlah());
			return rd;
		} catch (MonevDataException e) {
			return r;
		}
	}
	
	@SuppressWarnings("unchecked")
	public RealisasiDana get(Kegiatan kegiatan, int bulan) throws MonevDataException {
		Query query = getSession().createQuery("SELECT r FROM RealisasiDana r WHERE r.kegiatan = :kegiatan and r.bulan = :bulan");
		query.setParameter("kegiatan", kegiatan);
		query.setParameter("bulan", bulan);

		List<RealisasiDana> ls = checkNull(query.list());
		return ls.get(0);
	}
}
